package com.hmys.api.controller;

import com.github.pagehelper.PageInfo;
import com.hmys.api.config.Constant;
import com.hmys.api.model.WebJob;
import com.hmys.api.model.WebNews;
import com.hmys.api.response.Result;
import com.hmys.api.response.ResultCode;
import com.hmys.api.response.ResultPage;
import com.hmys.api.service.WebJobService;
import com.hmys.api.utils.FileUtil;
import com.hmys.api.utils.MailUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by chen365 on 2018/03/23.
 */
@RestController
@Api(tags = "招聘")
@RequestMapping(value = "/job")
public class JobController {
    @Autowired
    private WebJobService webJobService;
    @Autowired
    private JavaMailSender mailSender; //自动注入的Bean

    @Value("${spring.mail.username}")
    private String Sender; //读取配置文件中的参数

    @ApiOperation(value = "列表", notes = "列表", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "int", name = "pageIndex", value = "页码", required = true, paramType = "path"),
            @ApiImplicitParam(dataType = "int", name = "pageSize", value = "每页数", required = true, paramType = "path")
    })
    @GetMapping(value = "/list/{pageIndex}/{pageSize}")
    public Object list(@PathVariable("pageIndex") Integer pageIndex, @PathVariable("pageSize") Integer pageSize) {
        WebJob record = new WebJob();
        record.setStatus(true);
        record.setSort(1);
        PageInfo<WebJob> pageInfo = webJobService.selectByBean(pageIndex, pageSize, record);
        if (pageInfo.getList().size() > 0) {
            return new ResultPage(ResultCode.SUCCESS, pageInfo);
        } else {
            return new Result<>(ResultCode.NOT_FOUND);
        }
    }

    @ApiOperation(value = "详情", notes = "详情", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "int", name = "id", value = "招聘ID", required = true, paramType = "path")
    })
    @GetMapping(value = "/detail/{id}")
    public Object detail(@PathVariable("id") Integer id) {
        if (!StringUtils.isEmpty(id) && id < 1) {
            return new Result<>(ResultCode.ERROR_PARAM);
        }
        WebJob record = webJobService.selectByPrimaryKey(id);
        if (record != null) {
            if (record.getStatus()) {
                return new Result<>(ResultCode.SUCCESS, record);
            } else {
                return new Result<>(ResultCode.HAVE_DELETED);
            }
        } else {
            return new Result<>(ResultCode.NOT_FOUND);
        }
    }

    @ApiOperation(value = "发简历", notes = "发简历", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "int", name = "id", value = "招聘ID", required = true, paramType = "path")
    })
    @PostMapping(value = "/send/email/{id}")
    public Object sendEmail(HttpServletRequest request, HttpServletResponse response,
                            HttpSession session, @RequestParam("myFile") MultipartFile myFile,
                            @PathVariable("id") Integer id) {
        WebJob record = webJobService.selectByPrimaryKey(id);
        if (record == null) {
            return new Result(ResultCode.NON_JOB);
        }
        MimeMessage message = null;
        try {
            if (!myFile.isEmpty()) {
                String originalFileName = myFile.getOriginalFilename();
                String ext = FilenameUtils.getExtension(originalFileName);
                String filename = UUID.randomUUID().toString() + "." + ext;
                String uploadPath = Constant.PIC_LOCATION;
                File file = new File(uploadPath, originalFileName);
                FileUtils.copyInputStreamToFile(myFile.getInputStream(), file);
                MailUtil.sendEmil("chen365@yeah.net","1qaz2wsx","应聘 " + record.getPosition(),
                        "chen365@yeah.net","应聘 " + record.getPosition(),file.getAbsolutePath());
//                message = mailSender.createMimeMessage();
//                MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
//                helper.setFrom(Sender);
//
//                String[] tos = new String[]{"429461542@qq.com", Sender};
//                helper.setTo(tos);
//                //helper.setTo(Sender);
//                helper.setSubject("应聘 " + record.getPosition());
//                helper.setText("应聘 " + record.getPosition());
//                //注意项目路径问题，自动补用项目路径
//                //FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/image/picture.jpg"));
//                //加入邮件
//                helper.addAttachment(originalFileName, file);
//
//                System.err.println("文件名称：" + originalFileName);
//                mailSender.send(message);
                FileUtils.deleteQuietly(file);
                return new Result(ResultCode.SUCCESS);
            } else {
                return new Result(ResultCode.EMPTY_PHOTO);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(ResultCode.ERROR_SEND_EMAIL);

    }
}
